from django.utils.safestring import mark_safe
# 自定义的分页组件
class Pagination(object):
    def __init__(self,request,queryset,plus=5,page_size=6,page_param="page"):
        self.page=request.GET.get(page_param,"1")
       
        if self.page.isdecimal():
            self.page=int(self.page)
        else:
            self.page=1
        self.page_size=page_size
        self.start=(self.page-1)*page_size
        self.end=self.page*page_size
        self.page_queryset=queryset[self.start:self.end]
       
        self.total_count=queryset.count()
        self.total_page_count,div=divmod(self.total_count,page_size)
        if div:
            self.total_page_count+=1
        #如果数据库的数据非常少
        if self.total_page_count <= 2*plus+1:
            self.start_page=1
            self.end_page=self.total_page_count
        else:
            if self.page<=plus:
                self.start_page=1
                self.end_page=2*plus+1
            else:
                if (self.page+plus)>self.total_page_count:
                    self.start_page=self.total_page_count-plus*2
                    self.end_page=self.total_page_count
                else:
                    self.start_page=self.page-plus
                    self.end_page=self.page+plus

    def html(self):
        self.page_str_list=[]
        if self.page>1:
            prev='<li><a href="?page={}">上一页</a></li>'.format(self.page-1)
        else:
            prev='<li><a href="?page={}">上一页</a></li>'.format(1)
        self.page_str_list.append(prev)
    
        for i in range(self.start_page,self.end_page+1):
            if i==self.page:
                ele='<li class="active"><a href="?page={}">{}</a></li>'.format(i,i)
            else:
                ele='<li><a href="?page={}">{}</a></li>'.format(i,i)
            self.page_str_list.append(ele)
        if self.page < self.total_page_count:
            prev='<li><a href="?page={}">下一页</a></li>'.format(self.page+1)
        else:
            prev='<li><a href="?page={}">下一页</a></li>'.format(self.total_page_count)
        self.page_str_list.append(prev)
        page_string=mark_safe("".join(self.page_str_list))
        return page_string